package handler

import (
	"io/ioutil"
	"log"
	"os"
	"time"
	db "ulcdkey/db"
	"ulcdkey/tool"

	"github.com/labstack/echo/v4"
)

func UploadFile(c echo.Context) error {
	var r ResponseResult
	t := time.Now()
	uid := tool.GetUid(c)

	m, err := c.FormFile("file")
	if err != nil {
		log.Println("UploadFile1:", err)
		r.Code = -1
		r.Msg = err.Error()
		return c.JSON(200, r)
	}
	f, err := m.Open()
	if err != nil {
		log.Println("UploadFile2:", err)
		r.Code = -1
		r.Msg = err.Error()
		return c.JSON(200, r)
	}

	path := "/file/" + time.Now().Format("2006-01-02/")
	err = os.MkdirAll("public"+path, 777)
	if err != nil {
		log.Println("UploadFile3:", err)
		r.Code = -1
		r.Msg = err.Error()
		return c.JSON(200, r)
	}
	b, err := ioutil.ReadAll(f)
	if err != nil {
		log.Println("UploadFile4:", err)
		r.Code = -1
		r.Msg = err.Error()
		return c.JSON(200, r)
	}

	files := new(db.File)
	id, urlStr, err := files.UploadFile(b, path, m.Filename)
	if err != nil {
		log.Println("UploadFile err:", err)
		r.Code = -1
		r.Msg = "上传文件失败,err=" + err.Error()
		return c.JSON(200, r)
	}
	r.Data = map[string]interface{}{"id": id, "url": urlStr}

	log.Println(c.Request().URL, "uid =", uid, "【耗时:", time.Now().Sub(t).Seconds(), "s】")
	return c.JSON(200, r)
}
